package com.example.blackmarket.module.RegisterAndLogin;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.blackmarket.R;
import com.example.blackmarket.entities.FailureResponse;
import com.example.blackmarket.module.Base.BaseActivity;
import com.example.blackmarket.module.Base.BaseApplication;
import com.example.blackmarket.module.Home.MainActivity;


public class LoginActivity extends BaseActivity implements LoginView {

    private EditText studentNumber;

    private EditText password;

    private Button login;

    private Button toRegister;

    private LoginPresenter loginPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init();
        loginPresenter = new LoginPresenter(this);

    }


    @Override
    protected void onBindView() {
        studentNumber = findViewById(R.id.student_number);
        password = findViewById(R.id.password);
        login = findViewById(R.id.login);
        toRegister = findViewById(R.id.toRegister);
    }

    @Override
    protected void setButtonClick() {
        login.setOnClickListener(this);
        toRegister.setOnClickListener(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.login;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                loginPresenter.login(studentNumber.getText().toString(), password.getText().toString());
                break;
            case R.id.toRegister:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void showSuccess(String token) {
        if (token==null){
            showToast("获取认证信息失败，请尝试重新登录");
            return;
        }
        Log.d("Login",token);
        BaseApplication.set("token", token);
        //保存用户名&密码
        BaseApplication.set("studentNumber",this.studentNumber.getText().toString());
        BaseApplication.set("password", this.password.getText().toString());
        showToast("登录成功");
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    @Override
    public void showFailure(Object response) {
        FailureResponse failureResponse = (FailureResponse) response;
        if (failureResponse.getStatus()==403){
            showToast("用户名或密码错误");
        }else if(failureResponse.getStatus()==401){
            Log.e("Login","登陆时验证了过期的token");
            //发送这种情况应该提供方法给用户清空SharePreference
        }
    }

    public void showToast(String msg){
        Toast.makeText(this, msg,Toast.LENGTH_SHORT).show();
    }
}
